<?php

namespace App\Http\Controllers\Admin;
use App\Http\Requests\Admin\AdManage\CreateRequest;
use App\Http\Requests\Admin\AdManage\UpdateRequest;
use App\Models\Admin\AdManage;
use App\Models\Admin\AdSite;
use App\Models\Admin\AdSlots;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyJob;
use Illuminate\Http\Request;
use Style;

class AdManageController extends CommonController{
    /**
     * 显示广告
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        $input = arrayFilter($request->only(['keyword','ad_site','ad_slots','status']));
        $ad_manage = AdManage::select('id','title','pic_url','ad_site','ad_slots','end_time','status','url_type','url')
            ->where(function ($query) use ($input) {
                $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
                if(strlen($keyword) > 0){
                    $query->where('title', 'like', '%'.$keyword.'%');
                }
            })->where(function ($query) use ($input) {
                $ad_site = (!empty($input['ad_site'])) ? $input['ad_site'] : '';
                if(strlen($ad_site) > 0){
                    $query->where('ad_site',$ad_site);
                }
            })->where(function ($query) use ($input) {
                $ad_slots = (!empty($input['ad_slots'])) ? $input['ad_slots'] : '';
                if(strlen($ad_slots) > 0){
                    $query->where('ad_slots',$ad_slots);
                }
            })->where(function ($query) use ($input) {
                $status = (!empty($input['status'])) ? $input['status'] : '';
                if(strlen($status) > 0){
                    $query->where('status',$status);
                }
            })
            ->orderBy('created_at','desc')
            ->paginate(20);
        if(count($ad_manage) > 0){
            foreach($ad_manage as $v){
                $v->end_time = substr($v->end_time,0,10);
                $adSlots = AdSlots::where('id', $v->ad_slots)->first(['ad_name']);
                $v->ad_slots_name = !empty($adSlots) ? $adSlots->ad_name : '';
                $adSite = AdSite::where('id', $v->ad_site)->first(['site_name']);
                $v->ad_site = !empty($adSite) ? $adSite->site_name : '';
                $v->ad_url = $v->url_type.'_'.$v->url;
            }
        }
        //dd($ad_manage);
        $ad_site = AdSite::get();
        $as_slots = AdSlots::get();
        return Style::view('admin.adsystem.ad_manage.index',compact('ad_manage','ad_site','as_slots','input'));
    }

    /**
     * 添加广告
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request){
        $companyJob = CompanyJob::where('id',$request->job_id)->first(['job_title','id','com_id','uid']);
        $companyBasic = CompanyBasic::where('id',$request->com_id)->first(['company_name','id','uid']);
        $ad_site = AdSite::select('id','site_name')->get();
        $ad_slots = AdSlots::select('id','ad_name','width','height')->get();
        foreach($ad_slots as $v){
            $v->ad_name = $v->ad_name . '【'.$v->width.'×'.$v->height.'】';
        }
        return Style::view('admin.adsystem.ad_manage.create',compact('ad_site','ad_slots','companyJob','companyBasic'));
    }

    /**
     * 添加广告提交
     * @param CreateRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(CreateRequest $request){
        $input = $request->only(['uid','com_id','title','url_type','url','pic_url','ad_slots','ad_site','width','height','start_time','end_time','explanation']);
        if ($request->hasFile('pic_url')) {
            $file=$request->file('pic_url');
            $extension = strtolower($file -> getClientOriginalExtension());
            //判断文件上传大小
            if($file ->getClientSize() > $file ->getMaxFilesize() ){
                return  back()->with('errors','文件大小最大只能上传2M！');
            }
            //判断是不是一个有效的文件
            if ($file->isValid()) {
                if (!in_array($extension, array('gif','jpg','jpeg','png'))){
                    return  back()->with('errors','文件类型只能为 png, jpeg , jpg 或 gif的图片！');
                }else{
                    $destinationPath = '/upload/adminad/'; //后台上传文件广告图片位置
                    $fileurl=date("Ym").'/';
                    $filename=time().strtolower(str_random(5)).'.'.$extension;//定义文件名
                    $request->file('pic_url')->move(public_path().$destinationPath.$fileurl,$filename);//把缓存文件移动到指定文件夹下
                    $input['pic_url'] =$fileurl.$filename;
                }
            }
        }else{
            return  back()->with('errors','您上传的文件不存在');
        }
        $result = AdManage::create($input);
        if($result){
            flash('广告位管理添加成功', 'success');
            return redirect('admin/ad_manage');
        }else{
            return back()->with('errors','广告位管理添加失败，请稍后重试！');
        }
    }

    /**
     * 显示广告
     * @param $id
     */
    public function show($id){

    }

    /**
     * 编辑广告
     * @param $id
     * @return mixed
     */
    public function edit($id){
        $ad_site = AdSite::select('id','site_name')->get();
        $ad_slots = AdSlots::select('id','ad_name','width','height')->get();
        foreach($ad_slots as $v){
            $v->ad_name = $v->ad_name . '【'.$v->width.'×'.$v->height.'】';
        }
        $adManage = AdManage::find($id);
        $adManage->width = !empty($adManage->width) ? $adManage->width : '';
        $adManage->height = !empty($adManage->height) ? $adManage->height : '';
        return Style::view('admin.adsystem.ad_manage.edit',compact('ad_site','ad_slots','adManage'));
    }

    /**
     * 更新广告
     * @param UpdateRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(UpdateRequest $request, $id){
        $input = $request->only(['title','url_type','url','pic_url','ad_slots','ad_site','width','height','start_time','end_time','explanation']);
        if ($request->hasFile('pic_url')) {
            $file=$request->file('pic_url');
            $extension = strtolower($file -> getClientOriginalExtension());
            //判断文件上传大小
            if($file ->getClientSize() > $file ->getMaxFilesize() ){
                return  back()->with('errors','文件大小最大只能上传2M！');
            }
            //判断是不是一个有效的文件
            if ($file->isValid()) {
                if (!in_array($extension, array('gif','jpg','jpeg','png'))){
                    return  back()->with('errors','文件类型只能为 png, jpeg , jpg 或 gif的图片！');
                }else{
                    $destinationPath = '/upload/adminad/'; //后台上传文件广告图片位置
                    $fileurl=date("Ym").'/';
                    $filename=time().strtolower(str_random(5)).'.'.$extension;//定义文件名
                    $request->file('pic_url')->move(public_path().$destinationPath.$fileurl,$filename);//把缓存文件移动到指定文件夹下
                    $input['pic_url'] =$fileurl.$filename;
                    //删除原文件
                    $oldfile=public_path().$destinationPath.AdManage::where('id',$id)->first(['pic_url'])->pic_url;
                    @unlink($oldfile);
                }
            }
        }else{
            $input['pic_url']=AdManage::where('id',$id)->first(['pic_url'])->pic_url;
        }

        $result = AdManage::where('id',$id)->update($input);
        if($result){
            flash('更新广告成功', 'success');
            return redirect('admin/ad_manage');
        }else{
            return back()->with('errors','更新前和更新后数据相同，更新失败！！');
        }
    }

    /**
     * 删除广告
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id){
        $adManage=AdManage::where('id',$id)->first(['pic_url']);
        $result = AdManage::where('id',$id)->delete();
        if($result){
            @unlink(public_path()."/upload/adminad/".$adManage->pic_url);
            return response()->json(['status' => 0,'msg' => '删除广告成功！']);
        }else{
            return response()->json(['status' => 1,'msg' => '删除广告失败，请稍后重试！']);
        }
    }

    /**
     * 激活广告
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function activation(Request $request){
        $selected_id = $request->input('selected_id.*');
        $input['status'] = 1;
        foreach($selected_id as $v){
            AdManage::where('id',$v)->update($input);
        }
        flash('激活广告成功', 'success');
        return redirect('admin/ad_manage');
    }

    /**
     * 屏蔽广告
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function shield(Request $request){
        $selected_id = $request->input('selected_id.*');
        $input['status'] = 2;
        foreach($selected_id as $v){
            AdManage::where('id',$v)->update($input);
        }
        flash('屏蔽广告成功', 'success');
        return redirect('admin/ad_manage');
    }
}
